import Koa from 'koa'
import path from 'path'
import { fileURLToPath } from 'url'

import { koaBody } from 'koa-body'

import koaStatic from 'koa-static'

import Router from '@koa/router'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const rootDir = path.join(__dirname, '..')
const publicDir = path.join(rootDir, 'public')

function initKoa(port, callback) {
  const app = new Koa()

  app.use(koaBody())
  app.use(koaStatic(publicDir))

  const router = new Router()

  callback({ app, router })

  app.use(router.routes())
  app.use(router.allowedMethods())

  app.listen(port)

  console.log(`启动成功：http://127.0.0.1:${port}`)
}

export default initKoa
